package com.kla.power.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.kla.power.config.LogPointer;
import com.kla.power.entity.*;
import com.kla.power.service.*;
import com.kla.power.util.*;
import com.kla.power.vo.RealAmountVO;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 设备：逆变器、汇流箱、电表、组件、微逆、机器人、无人机 前端控制器
 * </p>
 * @author WuZH
 * @since 2023-06-23
 */
@RestController
@RequestMapping ("/device")
@CrossOrigin (value = "*", maxAge = 3600)
public class DeviceController {

    @Resource
    private IDeviceService iDeviceService;
    @Resource
    private IInverterElectricService iInverterElectricService;
    @Resource
    private IStationService iStationService;
    @Resource
    private IInverterAcAmountService iInverterAcAmountService;
    @Resource
    private IInverterDcAmountService iInverterDcAmountService;
    @Resource
    private IInverterAmountStatisticsDayService iInverterAmountStatisticsDayService;

    @RequestMapping ("queryList")
    @LogPointer ("设备列表查询")
    public ResultBody queryList (@RequestBody DeviceEntity deviceEntity) {
        UserEntity userEntity = (UserEntity) RedisUtils.get ( deviceEntity.getToken () );
        deviceEntity.setMerchantId ( userEntity.getMerchantId () );
        List<DeviceEntity> deviceEntities = iDeviceService.queryList ( deviceEntity );
        if ( deviceEntities != null ) {
            for ( DeviceEntity entity : deviceEntities ) {
                entity.setLastCreateTime ( CommonUtil.getDateStrFormat ( entity.getCreateTime (), "yyyy-MM-dd HH:mm:ss" ) );
            }
        }
        return ResultBody.success ( deviceEntities );
    }

    @RequestMapping ("queryCount")
    @LogPointer ("设备列表总数")
    public ResultBody queryCount (@RequestBody DeviceEntity deviceEntity) {
        UserEntity userEntity = (UserEntity) RedisUtils.get ( deviceEntity.getToken () );
        deviceEntity.setMerchantId ( userEntity.getMerchantId () );
        Integer count = iDeviceService.queryCount ( deviceEntity );
        return ResultBody.success ( count );
    }

    @RequestMapping ("updateSingle")
    @LogPointer ("更新设备信息")
    public ResultBody updateSingle (@RequestBody DeviceEntity deviceEntity) {
        deviceEntity = iDeviceService.updateSingle ( deviceEntity );
        return ResultBody.success ( deviceEntity );
    }

    @RequestMapping ("saveSingle")
    @LogPointer ("保存设备")
    public ResultBody saveSingle (@RequestBody DeviceEntity deviceEntity) {
        // 根据SN查询设备是否已添加
        DeviceEntity device = iDeviceService.querySingle ( deviceEntity );
        if ( device != null ) {
            return ResultBody.fail ( StateEnum.SN_UNION_EXCE );
        }
        deviceEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        deviceEntity = iDeviceService.saveSingle ( deviceEntity );
        return ResultBody.success ( deviceEntity );
    }


    @RequestMapping ("querySingle")
    @LogPointer ("查询设备信息")
    public ResultBody querySingle (@RequestBody DeviceEntity deviceEntity) {
        deviceEntity = iDeviceService.querySingle ( deviceEntity );
        return ResultBody.success ( deviceEntity );
    }

    /**
     * 连接信息列表
     * @param deviceEntity
     * @return
     */
    @RequestMapping ("connection")
    @LogPointer ("连接信息")
    public ResultBody connection (@RequestBody DeviceEntity deviceEntity) {
        DeviceEntity connection = iDeviceService.connection ( deviceEntity );
        return ResultBody.success ( connection );
    }

    /**
     * 1.查询设备详情
     * 2.查询直流和交流发电量
     * 3.查询历史数据
     * @param deviceEntity
     * @return
     */
        @RequestMapping ("queryInverterDetails")
    @LogPointer ("查询逆变器详情")
    public ResultBody queryInverterDetails (@RequestBody DeviceEntity deviceEntity) {
        Map<String, Object> map = iDeviceService.queryInverterDetails ( deviceEntity );
        return ResultBody.success ( map );
    }

    /**
     * 交流和月度年度发电量历史数据
     * @param deviceEntity
     * @return
     */
    @RequestMapping ("historyData")
    @LogPointer ("逆变器交流发电历史")
    public ResultBody historyData (@RequestBody DeviceEntity deviceEntity) {
        Map<Object, Object> map = iDeviceService.queryInverterHistoryData ( deviceEntity );
        return ResultBody.success ( map );
    }


    /**
     * 直流历史数据
     * @param deviceEntity
     * @return
     */
    @RequestMapping ("dcHistoryData")
    @LogPointer ("逆变器直流发电历史")
    public ResultBody dcHistoryData (@RequestBody DeviceEntity deviceEntity) {
        Map<Object, Object> map = iDeviceService.queryDcHistoryData ( deviceEntity );
        return ResultBody.success ( map );
    }


    /**
     * 逆变器详情页总直流功率和总有功功率
     * @param deviceEntity {
     *                     createTime：查询某一天
     *                     }
     * @return
     */
    @RequestMapping ("dcPowerList")
    @LogPointer ("逆变器实时功率列表")
    public ResultBody dcPowerList (@RequestBody DeviceEntity deviceEntity) {
        DeviceEntity device = iDeviceService.querySingle ( deviceEntity );
        List<InverterElectricEntity> inverterSystemEntities = iInverterElectricService.getBaseMapper ().selectList ( new QueryWrapper<InverterElectricEntity> ().eq ( "serialNumber", device.getDeviceSn () ).eq ( "DATE_FORMAT (createTime,'%Y-%m-%d')", CommonUtil.getDateStrFormat ( deviceEntity.getCreateTime (), "yyyy-MM-dd" ) ) );
        List<RealAmountVO> realAmountVOS = new ArrayList<> ();
        for ( InverterElectricEntity inverterSystemEntity : inverterSystemEntities ) {
            RealAmountVO vo = new RealAmountVO ();
            vo.setCreateTime ( CommonUtil.getDateStrFormat ( inverterSystemEntity.getCreateTime (), "HH:mm:ss" ) );
            vo.setTodayEnergy ( inverterSystemEntity.getTodayEnergy () );
            vo.setGridPower ( inverterSystemEntity.getGridPower () );
            realAmountVOS.add ( vo );
        }
        return ResultBody.success ( realAmountVOS );
    }


    /**
     * 下载逆变器发电历史数据
     * @param deviceEntity
     */
    @RequestMapping ("download")
    public void download (@RequestBody DeviceEntity deviceEntity, HttpServletResponse response) throws Exception {
        if ( deviceEntity.getTimeType () == 1 || deviceEntity.getTimeType () == 2 ) {
            // 下载指定某一天明细，直流、交流明细
            List<List<String>> title = parseInverterAcDcTitle ();
            List<List<String>> data = parseInverterAcDcData ( deviceEntity );
            String excelTitle = CommonUtil.getDateStrFormat ( deviceEntity.getStartTime (), "yyyy-MM-dd" ) + "~" + CommonUtil.getDateStrFormat ( deviceEntity.getEndTime (), "yyyy-MM-dd" ) + "发电数据报表";
            DynamicEasyExcelExportUtils.parseExcel ( response, excelTitle, title, data );
        } else if ( deviceEntity.getTimeType () == 3 || deviceEntity.getTimeType () == 4 ) {
            // 下载指定一个月的数据
            List<List<String>> title = parseInverterAmountTitle ();
            List<List<String>> lists = parseInverterAmountContent ( deviceEntity );
            String excelTitle = CommonUtil.getDateStrFormat ( deviceEntity.getStartTime (), "yyyy-MM-dd" ) + "~" + CommonUtil.getDateStrFormat ( deviceEntity.getEndTime (), "yyyy-MM-dd" ) + "发电数据报表";
            DynamicEasyExcelExportUtils.parseExcel ( response, excelTitle, title, lists );
        }
    }


    /**
     * 生成逆变器发电表格内容
     * @param deviceEntity
     * @return
     */
    private List<List<String>> parseInverterAmountContent (DeviceEntity deviceEntity) {
        List<List<String>> content = Lists.newArrayList ();
        // 设备信息
        DeviceEntity device = iDeviceService.querySingle ( deviceEntity );
        // 电站信息
        StationEntity stationEntity = new StationEntity ();
        stationEntity.setId ( device.getStationId () );
        StationEntity station = iStationService.querySingle ( stationEntity );
        // 该逆变器今天的发电数据
        InverterElectricEntity inverterElectricEntity = new InverterElectricEntity ();
        inverterElectricEntity.setSerialNumber ( device.getDeviceSn () );
        InverterElectricEntity inverterElectric = iInverterElectricService.queryInverterTodayMax ( inverterElectricEntity );
        // 查询每天发电数据
        InverterAmountStatisticsDayEntity inverterAmountStatisticsDayEntity = new InverterAmountStatisticsDayEntity ();
        inverterAmountStatisticsDayEntity.setInverterSn ( device.getDeviceSn () );
        inverterAmountStatisticsDayEntity.setStartTime ( deviceEntity.getStartTime () );
        inverterAmountStatisticsDayEntity.setEndTime ( deviceEntity.getEndTime () );
        List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = iInverterAmountStatisticsDayService.queryHistoryList ( inverterAmountStatisticsDayEntity );
        for ( int i = 0; i < inverterAmountStatisticsDayEntities.size (); i++ ) {
            List<String> data = Lists.newArrayList (
                    device.getDeviceTitle (), device.getDeviceSn (), station.getStationName (), "数采", CommonUtil.getDateStrFormat ( inverterAmountStatisticsDayEntities.get ( i ).getCollectorTime (), "yyyy-MM-dd" ),
                    inverterAmountStatisticsDayEntities.get ( i ).getYesterdayPower ()
            );
            content.add ( data );
        }
        if ( inverterElectric != null ) {
            List<String> data = Lists.newArrayList (
                    device.getDeviceTitle (), device.getDeviceSn (), station.getStationName (), "数采", CommonUtil.getDateStrFormat ( new Date (), "yyyy-MM-dd" ), inverterElectric.getTodayEnergy ()
            );
            content.add ( data );
        }
        return content;
    }

    /**
     * 生成逆变器直流，交流，发电表头
     * @return
     */
    private List<List<String>> parseInverterAcDcTitle () {
        List<String> title = new ArrayList<> ();
        title.add ( "名称" );
        title.add ( "SN" );
        title.add ( "所属电站" );
        title.add ( "父设备" );
        title.add ( "型号名称" );
        title.add ( "制造商名称" );
        title.add ( "数据更新时间" );
        title.add ( "当日发电量(KWh)" );
        title.add ( "当日满发小时(H)" );
        title.add ( "直流PV1电流（A）" );
        title.add ( "直流PV2电流（A）" );
        title.add ( "直流PV1电压（V）" );
        title.add ( "直流PV2电压（V）" );
        title.add ( "直流PV1功率（W）" );
        title.add ( "直流PV2功率（W）" );
        title.add ( "交流电压R/U/A（V）" );
        title.add ( "交流电压S/V/B（V）" );
        title.add ( "交流输出频率R（Hz）" );
        title.add ( "交流输出总功率（有功）（W）" );
        title.add ( "累计发电量（有功）（kWh）" );
        List<List<String>> allHead = new ArrayList<> ();
        allHead.add ( title );
        return allHead;
    }


    /**
     * 生成逆变器内容
     * 查询逆变器详情，以及直流、交流相关数据
     * @param deviceEntity
     * @return
     */
    private List<List<String>> parseInverterAcDcData (DeviceEntity deviceEntity) {
        List<List<String>> content = Lists.newArrayList ();
        // 设备信息
        DeviceEntity device = iDeviceService.querySingle ( deviceEntity );
        // 电站信息
        StationEntity stationEntity = new StationEntity ();
        stationEntity.setId ( device.getStationId () );
        StationEntity station = iStationService.querySingle ( stationEntity );
        // 发电信息
        InverterElectricEntity inverterElectricEntity = new InverterElectricEntity ();
        inverterElectricEntity.setSerialNumber ( device.getDeviceSn () );
        inverterElectricEntity.setStartTime ( device.getStartTime () );
        inverterElectricEntity.setEndTime ( device.getEndTime () );
        List<InverterElectricEntity> inverterElectricEntities = iInverterElectricService.queryHistoryData ( inverterElectricEntity );
        // 直流交流数据
        InverterAcAmountEntity inverterAcAmountEntity = new InverterAcAmountEntity ();
        inverterAcAmountEntity.setInverterSn ( device.getDeviceSn () );
        inverterAcAmountEntity.setStartTime ( deviceEntity.getStartTime () );
        inverterAcAmountEntity.setEndTime ( deviceEntity.getEndTime () );
        List<InverterAcAmountEntity> inverterAcAmountEntities = iInverterAcAmountService.queryHistoryData ( inverterAcAmountEntity );
        InverterDcAmountEntity inverterDcAmountEntity = new InverterDcAmountEntity ();
        inverterDcAmountEntity.setStartTime ( deviceEntity.getStartTime () );
        inverterDcAmountEntity.setEndTime ( deviceEntity.getEndTime () );
        inverterDcAmountEntity.setInverterSn ( device.getDeviceSn () );
        List<InverterDcAmountEntity> inverterDcAmountEntities = iInverterDcAmountService.queryHistoryData ( inverterDcAmountEntity );
        for ( InverterElectricEntity systemEntity : inverterElectricEntities ) {
            String pv1Curr = "", pv2Curr = "", pv1Voltage = "", pv2Voltage = "", pv1Power = "", pv2Power = "", acVoltageR = "", acCurrR = "",acRateR = "";
            for ( InverterAcAmountEntity acAmountEntity : inverterAcAmountEntities ) {
                if ( systemEntity.getCreateTime ().compareTo ( acAmountEntity.getCreateTime () ) == 0 && acAmountEntity.getTitle ().equals ( "交流1" ) ) {
                    acVoltageR = acAmountEntity.getVoltage ();
                    acCurrR = acAmountEntity.getCurrent ();
                    acRateR = acAmountEntity.getRate ();
                }
            }
            for ( InverterDcAmountEntity dcAmountEntity : inverterDcAmountEntities ) {
                if ( systemEntity.getCreateTime ().compareTo ( dcAmountEntity.getCreateTime () ) == 0 && dcAmountEntity.getSort () == 1 ) {
                    pv1Curr = dcAmountEntity.getCurrent ();
                    pv1Voltage = dcAmountEntity.getVoltage ();
                    pv1Power = dcAmountEntity.getPower ();
                } else if ( systemEntity.getCreateTime ().compareTo ( dcAmountEntity.getCreateTime () ) == 0 && dcAmountEntity.getSort () == 2 ) {
                    pv2Curr = dcAmountEntity.getCurrent ();
                    pv2Voltage = dcAmountEntity.getVoltage ();
                    pv2Power = dcAmountEntity.getPower ();
                }
            }
            List<String> data = Lists.newArrayList ( device.getDeviceTitle (), device.getDeviceSn (), station.getStationName (), systemEntity.getCollectorSn (),
                                                     systemEntity.getMadelName (), systemEntity.getManufacturer (),
                                                     CommonUtil.getDateStrFormat ( systemEntity.getCreateTime (), "yyyy-MM-dd HH:mm:ss" ), systemEntity.getTodayEnergy (), CommonUtil.divided ( Double.parseDouble ( systemEntity.getTodayEnergy () ), Double.parseDouble ( device.getPower()  ) ),
                                                     pv1Curr, pv2Curr, pv1Voltage, pv2Voltage, pv1Power, pv2Power, acVoltageR, acCurrR, acRateR,
                                                     systemEntity.getGridPower (),  systemEntity.getTodayEnergy ()
            );
            content.add ( data );
        }
        return content;
    }



    /**
     * 生成逆变器发电表头
     * @return
     */
    private List<List<String>> parseInverterAmountTitle () {
        List<String> title = new ArrayList<> ();
        title.add ( "名称" );
        title.add ( "SN" );
        title.add ( "所属电站" );
        title.add ( "父设备" );
        title.add ( "时间" );
        title.add ( "发电量(kWh)" );
        List<List<String>> allHead = new ArrayList<> ();
        allHead.add ( title );
        return allHead;
    }

}
